package com.das.mechanic_base.adapter.common;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.bean.task.SaveTodoBean;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3LoadingHolder;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class X3HomeTaskAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<SaveTodoBean> mList;

    private Context mContext;

    private String today;

    private final Drawable notComplete,complete;

    private boolean isExpand;

    /**
     * 0 正常
     * 1 空白占位
     * 2 loading
     */
    private int mEmptyType;

    private boolean isWhite;
    private int addIndex;

    public X3HomeTaskAdapter(Context mContext) {
        this.mContext = mContext;
        this.mList = new ArrayList<>();

        notComplete = mContext.getResources().getDrawable(R.mipmap.x3_task_not_complete_time);
        notComplete.setBounds(0, 0, notComplete.getMinimumWidth(), notComplete.getMinimumHeight());

        complete = mContext.getResources().getDrawable(R.mipmap.x3_task_complete_time);
        complete.setBounds(0, 0, complete.getMinimumWidth(), complete.getMinimumHeight());

        mEmptyType = 2;
    }

    public void changeHomeTask(List<SaveTodoBean> mList,boolean isWhite,int addIndex) {
        this.mList = mList;
        this.isWhite = isWhite;
        this.addIndex = addIndex;

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//如果用到别的就用特定
        //字符表示，如星期F
        today = sdf.format(d);

        mEmptyType = X3StringUtils.isListEmpty(mList) ? 1 : 0;
        notifyDataSetChanged();
        changeExpand(false);
    }

    public int getAddIndex() {
        return addIndex;
    }

    /**
     * 上拉加载
     * @param mList
     */
    public void addHomeTask(List<SaveTodoBean> mList) {
        this.mList.addAll(mList);
        mEmptyType = X3StringUtils.isListEmpty(mList) ? 1 : 0;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case 1:
                return new EmptyHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_empty_home_task_item, parent, false));
            case 2:
                return new X3LoadingHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_home_loading_item, parent, false));
            default:
                return new HomeTaskHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_home_task_item_layout, parent, false));
        }
    }

    public void changeExpand(boolean isExpand) {
        this.isExpand = isExpand;
        notifyItemRangeChanged(addIndex,mList.size() - addIndex);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        int itemViewType = getItemViewType(position);
        switch (itemViewType) {
            case 0:
                HomeTaskHolder taskHolder = (HomeTaskHolder) holder;

                taskHolder.itemView.setBackgroundColor(isWhite ? Color.WHITE : 0);

                if (position <= addIndex) {
                    taskHolder.rl_task.setVisibility(X3StringUtils.isEmpty(mList.get(position).content) ? View.GONE : View.VISIBLE);
                }else {
                    taskHolder.rl_task.setVisibility(isExpand ? View.VISIBLE : View.GONE);
                }

                taskHolder.tv_content.setTextColor(mList.get(position).isComplete ? Color.parseColor("#B1B3BD") : Color.parseColor("#313340"));

                taskHolder.tv_content.getPaint().setFlags(mList.get(position).isComplete ? Paint. STRIKE_THRU_TEXT_FLAG : 0); //中间横线（删除线）

                taskHolder.ll_add.setVisibility((position == addIndex) ? View.VISIBLE : View.GONE);

                taskHolder.v_line.setVisibility((position == addIndex) ? View.GONE : View.VISIBLE);

                if (!X3StringUtils.isEmpty(mList.get(position).content)) {
                    String content = mList.get(position).content.replaceAll("<em>", "<font color='#0077FF'>").replaceAll("</em>", "</font>");

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        taskHolder.tv_content.setText(Html.fromHtml(content,0));
                    }else {
                        taskHolder.tv_content.setText(Html.fromHtml(content));
                    }
                }else {
                    taskHolder.tv_content.setText(mList.get(position).content + "");
                }

                String priorityLevel = mList.get(position).priorityLevel;

                if (mList.get(position).isComplete) {
                    taskHolder.iv_status.setImageResource(R.mipmap.x3_task_complete);
                }else {
                    if ("LEVEL_MI".equals(priorityLevel)) {
                        taskHolder.iv_status.setImageResource(R.mipmap.x3_task_mi);

                    }else if("LEVEL_HI".equals(priorityLevel)) {
                        taskHolder.iv_status.setImageResource(R.mipmap.x3_task_hi);

                    }else {
                        taskHolder.iv_status.setImageResource(R.mipmap.x3_task_normal);

                    }
                }

                String remindTime = mList.get(position).remindTime;
                taskHolder.tv_time.setVisibility(X3StringUtils.isEmpty(remindTime) ? View.GONE : View.VISIBLE);
                if (!X3StringUtils.isEmpty(remindTime)) {
                    String taskTimeAfter = X3DateUtils.HomeLongDateWithTime(remindTime,mContext);
                    taskHolder.tv_time.setText(String.format(mContext.getString(R.string.task_remind_time),taskTimeAfter));

                    if (mList.get(position).isComplete) {
                        taskHolder.tv_time.setTextColor(Color.parseColor("#B1B3BD"));
                        taskHolder.tv_time.setCompoundDrawables(notComplete, null, null, null);

                    }else {
                        boolean timeCompareSize = X3TimeUtils.getNewTimeCompareSize(today, remindTime);
                        if (!timeCompareSize) {
                            taskHolder.tv_time.setTextColor(Color.parseColor("#F64458"));
                            taskHolder.tv_time.setCompoundDrawables(complete, null, null, null);
                        }else {
                            taskHolder.tv_time.setTextColor(Color.parseColor("#B1B3BD"));
                            taskHolder.tv_time.setCompoundDrawables(notComplete, null, null, null);
                        }
                    }
                }

                String carOwnerUserName = X3StringUtils.isEmpty(mList.get(position).carOwnerUserName) ? "" : mList.get(position).carOwnerUserName;
                taskHolder.tv_user.setVisibility(X3StringUtils.isEmpty(carOwnerUserName) ? View.GONE : View.VISIBLE);
                taskHolder.tv_user.setText(carOwnerUserName);

                holder.itemView.setOnClickListener(v -> {
                    if (iOnShowTask != null) {
                        iOnShowTask.iOnShowOrCreateTask(mList.get(position).id);
                    }
                });

                taskHolder.ll_add.setOnClickListener(v -> {
                    if (iOnShowTask != null) {
                        iOnShowTask.iOnShowOrCreateTask(0);
                    }
                });

                taskHolder.rl_status.setOnClickListener(v -> {
                    if (iOnShowTask != null) {
                        iOnShowTask.iOnIsCompleteTask(mList.get(position).isComplete,mList.get(position).id);
                    }
                });


                break;
            case 1:
                EmptyHolder emptyHolder = (EmptyHolder) holder;
                emptyHolder.rl_create.setOnClickListener(v -> {
                    if (iOnShowTask != null) {
                        iOnShowTask.iOnShowOrCreateTask(0);
                    }
                });
                break;
        }
    }

    public boolean isGroupHead(int position) {
        if (X3StringUtils.isListEmpty(mList)) {
            return false;
        }
        if (position >= mList.size()) {
            return false;
        }
        if (position == 0) {
            return true;
        } else {
            String currentGroup = getGroupName(position);
            String preGroup = getGroupName(position - 1);

            return !currentGroup.equals(preGroup);
        }
    }

    public boolean isComplete(int position) {
        if (position >= mList.size()) {
            return false;
        }
        return mList.get(position).isComplete;
    }

    /**
     * 获取组名
     */
    public String getGroupName(int position){
        if (X3StringUtils.isListEmpty(mList)) {
            return "";
        }
        if (position >= mList.size() || position < 0) {
            return "";
        }
        return mList.get(position).groupHeader;
    }

    public String getCompleteName() {
        if (isExpand) {
            return mContext.getString(R.string.task_gone);
        }
        return mContext.getString(R.string.task_list_show);
    }

    /**
     * 是否是展开状态
     * @return
     */
    public boolean isExpand() {
        return isExpand;
    }

    public int getWidth() {
        return X3ScreenUtils.getScreenWidth(mContext);
    }

    @Override
    public int getItemViewType(int position) {
        return mEmptyType;
    }

    IOnShowTask iOnShowTask;

    public void setiOnShowTask(IOnShowTask iOnShowTask) {
        this.iOnShowTask = iOnShowTask;
    }

    public interface IOnShowTask {
        void iOnShowOrCreateTask(long id);

        void iOnIsCompleteTask(boolean isComplete,long id);
    }

    @Override
    public int getItemCount() {
        return X3StringUtils.isListEmpty(mList) ? 1 : mList.size();
    }

    public class HomeTaskHolder extends RecyclerView.ViewHolder {
        LinearLayout ll_add;
        View v_line;
        RelativeLayout rl_status;
        ImageView iv_status;
        TextView tv_content;
        TextView tv_time;
        TextView tv_user;
        RelativeLayout rl_task;

        public HomeTaskHolder(@NonNull View itemView) {
            super(itemView);
            ll_add = itemView.findViewById(R.id.ll_add);
            v_line = itemView.findViewById(R.id.v_line);
            rl_status = itemView.findViewById(R.id.rl_status);
            iv_status = itemView.findViewById(R.id.iv_status);
            tv_content = itemView.findViewById(R.id.tv_content);
            tv_time = itemView.findViewById(R.id.tv_time);
            tv_user = itemView.findViewById(R.id.tv_user);
            rl_task = itemView.findViewById(R.id.rl_task);
        }
    }

    public class EmptyHolder extends RecyclerView.ViewHolder {
        RelativeLayout rl_create;
        public EmptyHolder(@NonNull View itemView) {
            super(itemView);
            rl_create = itemView.findViewById(R.id.rl_create);
        }
    }
}
